import { createRouter, createWebHashHistory } from "vue-router";
import keepAliveRouter from '@/utils/keepAlive.js';
import store from "@/store";
const context = import.meta.globEager("./**/*.ts");
let routeList: Array<any> = [];
Object.keys(context).forEach((route) => {
  routeList = routeList.concat(context[route].default);
});
const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      redirect: { name: "Login" },
    },
    {
      path: "/main",
      name: "Main",
      component: () => import("@/views/Main.vue"),
      children: routeList.concat(
        {
          path: "/403",
          name: "403",
          component: () => import("@/views/exception/403.vue"),
          meta: {
            isNone: true,
            noChild: true,
            needLogin: false,
          },
        },
        {
          path: "/:pathMatch(.*)*",
          name: "404",
          component: () => import("@/views/exception/404.vue"),
          meta: {
            isNone: true,
            noChild: true,
            needLogin: false,
          },
        }
      ),
    },
    {
      path: "/example",
      name: "Example",
      component: () => import("@/views/example/index.vue"),
    },
    {
      path: "/tools",
      name: "tools",
      component: () => import("@/views/tools/Index.vue"),
    },
    {
      path: "/login",
      name: "Login",
      component: () => import("@/views/passport/login.vue"),
      meta: {
        title: "登录",
        needLogin: false,
      },
    },
    {
      path: "/login/input",
      name: "LoginInput",
      component: () => import("@/views/passport/login.vue"),
      meta: {
        title: "登录",
        needLogin: false,
        modeType: 'input'
      },
    },
    {
      path: "/white",
      name: "White",
      component: () => import("@/views/passport/white.vue"),
      meta: {
        title: "中间页免登录",
        needLogin: false,
      },
    },
    {
      path: "/qrcode_login_mobile",
      name: "QrcodeLoginMobile",
      component: () => import("@/views/passport/QrcodeLoginMobile.vue"),
      meta: {
        title: "二维码登录-选择账号",
        needLogin: false,
      },
    },
    {
      path: "/bind_wechat_mobile",
      name: "BindWechatMobile",
      component: () => import("@/views/organization/BindWechatMobile.vue"),
      meta: {
        title: "绑定微信账号",
        needLogin: false,
      },
    },
    {
      path: "/flow/auto/marketingProcess/workTable",
      name: "WorkTable",
      meta: {
        title: "新建流程图",
        isNone: true,
        needLogin: false,
        noChild: true,
      },
      component: () => import("@/views/workTable/workTable.vue"),
    },
    {
      path: "/activity/pageList/createEditApp/:id",
      name: "CreateEdit",
      meta: {
        title: "活动页面配置",
        isNone: true,
        needLogin: true,
        noChild: true,
      },
      component: () => import("@/views/activity/actApp/createEdit.vue"),
    },
    {
      path: "/mall/decorate/page/store_app/:mallId/:id",
      name: "StoreApp",
      meta: {
        title: "商城页面配置",
        isNone: true,
        needLogin: true,
        noChild: true,
      },
      component: () => import("@/views/activity/actApp/storeEdit.vue"),
    },
    {
      path: "/activity-design",
      name: "ActivityDesign",
      component: () =>
        import("@/views/activity/activityManage/ActivityTempl.vue"),
      meta: {
        title: "活动模板",
        needLogin: false,
      },
    },
    {
      path: "/activity/templateMng/design/:id?",
      name: "ActivityDesignPrivate",
      component: () =>
        import("@/views/activity/templateManage/TemplateForm.vue"),
      meta: {
        title: "活动模板",
        needLogin: false,
      },
    },
    {
      path: "/activity/list/add/:id/:copyId?",
      name: "ActivityAdd",
      component: () =>
        import("@/views/activity/activityManage/ActivityForm.vue"),
      meta: {
        title: "新增活动",
        needLogin: true,
      },
    },
    {
      path: "/activity/list/:mode(edit|detail)/:id",
      name: "ActivityEdit",
      component: () =>
        import("@/views/activity/activityManage/ActivityForm.vue"),
      meta: {
        title: "编辑活动",
        needLogin: true,
      },
    },
    {
      path: "/mall/manage/list",
      name: 'MallManageList',
      component: () => import("@/views/pointsMall/MallList.vue"),
      meta: {
        title: "商城列表",
        needLogin: true,
        hideMenu: true,
        keepAlive: true,
      },
    },
    {
      path: "/database/dataBoard",
      name: "DataBoard",
      component: () => import("@/views/dataCenter/dataBoard/index.vue"),
      meta: {
        title: "营销数据驾驶舱首页",
        hideMenu: true,
      },
    },
    {
      path: "/mock/task_center",
      name: "TaskCenter",
      component: () => import("@/views/mock/taskCenter.vue"),
      meta: {
        title: "回调测试",
        needLogin: false,
      },
    },
    {
      path: "/messageCenter/pastRecords",
      name: "PastRecords",
      component: () => import("@/views/pastRecords/index.vue"),
      meta: {
        title: "消息历史",
        hideMenu: true,
      },
    },
    //登录页模板制作
    {
      path: "/merchant/pageMng/addLogin/:id?",
      name: "AddLogin",
      meta: {
        title: "登录页管理",
        needLogin: true,
        keepAlive: true,
      },
      component: () => import("@/views/page/addLogin.vue"),
    },
  ],
});
router.beforeEach((to, from, next) => {
  // NProgress.start();
  document.title =
    to.meta.title || (window as any).VUE_APP_URL[import.meta.env.MODE].title;
  const token = store.state.user.token;
  // 全局缓存监听
  let tapRouterList = store.state.bookList.bookList;
  let routerArr: Array<any> = [];
  if (Object.keys(tapRouterList).length != 0) {
    tapRouterList['ACTIVITY'] && tapRouterList['ACTIVITY'].forEach((item: any) => {
      keepAliveRouter.forEach((value: any) => {
        if (item === value.path) {
          routerArr.push(value.name)
        }
      })
    })
    tapRouterList['FLOW'] && tapRouterList['FLOW'].forEach((item: any) => {
      keepAliveRouter.forEach((value: any) => {
        if (item === value.path) {
          routerArr.push(value.name)
        }
      })
    })
    tapRouterList['MALL'] && tapRouterList['MALL'].forEach((item: any) => {
      keepAliveRouter.forEach((value: any) => {
        if (item === value.path) {
          routerArr.push(value.name)
        }
      })
    })
    tapRouterList['MARKETING'] && tapRouterList['MARKETING'].forEach((item: any) => {
      keepAliveRouter.forEach((value: any) => {
        if (item === value.path) {
          routerArr.push(value.name)
        }
      })
    })
    tapRouterList['MERCHANT'] && tapRouterList['MERCHANT'].forEach((item: any) => {
      keepAliveRouter.forEach((value: any) => {
        if (item === value.path) {
          routerArr.push(value.name)
        }
      })
    })
    store.commit('SETKEEPALIVEINCLUDE', routerArr);
    // console.log('routerArr', routerArr)
  }
  // 免校验
  if (to.path == "/login" || to.path == '/login/input') {
    next();
    return;
  }
  if (to.meta.needLogin === false) {
    next();
    return;
  }
  if (to.meta.needLogin === true && !token) {
    const path = sessionStorage.getItem('loginPath') || '/login'
    const url=path.split("?")[0]
    router.replace({
      path: url,
      query: { redirectUrl: encodeURIComponent(to.fullPath) },
    });
  } else {
    const aa = to.path.split('/')[1].toUpperCase()
    if (aa != 'LOGIN' && aa != store.state.user.currentService) {
      store.commit('SETCURRENTSERVICE', aa)
    }
    next();
  }

});

router.afterEach(() => {
  // NProgress.done();
});

export default router;
